package com.hp.ssmp.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class QiniuUtils {
    //AK
    private static final String accessKey = "f0Zh_78zHXqldeiL_PvJTJkrnXtniwhVuHooutFo";
    //SK
    private static final String secretKey = "EqWTACtvvB7yit0-UOmW8zJ_6qgiZHIxI-p0tIac";
    //空间
    private static final String bucket = "chenshuai";

    private static final String qiniuUrl = "http://sbamdn6je.hn-bkt.clouddn.com/";

    public static R upload(InputStream is, String fileName){
        ObjectMapper mapper = new ObjectMapper();

        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String ext=fileName.substring(fileName.lastIndexOf("."));
        String key = UUID.randomUUID().toString()+ext;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(is, key, upToken,null,null);
            DefaultPutRet putRet = mapper.readValue(response.bodyString(), DefaultPutRet.class);
            return  R.success(qiniuUrl + putRet.key);
        } catch (Exception ex) {
            return  R.error();
        }

    }
}
